package cn.com.callback

import cn.com.elite.EliteBean
import cn.com.elite.Util
import cn.com.kh.KHUtil
import cn.com.kh.getProperty
import org.json.JSONObject
import org.slf4j.Logger
import org.slf4j.LoggerFactory

/**
 * 华盛通开户名单下发线程任务
 */

public class autoHSTCustIssued implements EliteThreadInvoke {
    private static final Logger log = LoggerFactory.getLogger(autoHSTCustIssued.class);

    public int doCallBack(EliteBean eliteBean, String content) {

        // 查询待处理名单
        log.debug("待处理名单线程Guid：" + content);

        List accountList = eliteBean.chaxun_sql("Select Rec_Id, Customerid, Customername, Gender, Phone, Accounttype, register_id, Registertime, Opentime, Inviter_Hstno, Inviter_Name, Inviter_Type From Account_Information Where Batch_Guid = '" + content + "'","dataSource");
        for (int i = 0; i < accountList.size(); i++) {
            long startTime = System.currentTimeMillis();
            Map accountMap = accountList.get(i);

            String Rec_Id = accountMap.get("Rec_Id");//处理任务主键
            String Customerid = accountMap.get("Customerid");//华盛号
            String register_id = accountMap.get("register_id");//注册渠道id
            String Inviter_Hstno = accountMap.get("Inviter_Hstno");//邀约华盛号

            String Rule_Id = null;
            String r_Control_Id = null;
            String r_Rolegroup_Id = null;
            String r_Staff_Id = null;
            String counselor_id = null;

            // 查询名单是否已经存在
            List custCountList = eliteBean.chaxun_sql("Select Customer_Guid From Customer Where Customer_Id = '" + Customerid + "'", "dataSource");

            if (custCountList.size() <= 0) {
                // 通过名单信息中渠道在规则表中找到优先级最高的规则
                String ruleCheckSQL = "Select Rule_Id, Rule_Name, Rolegroup, Staff_Id, Order_Adjustment From Hst_Rule_Issue Where Rule_State = 1 And Find_In_Set('" + register_id + "', Code_Id) > 0 Order By Order_Adjustment Limit 1";

                List ruleCheckList = eliteBean.chaxun_sql(ruleCheckSQL, "dataSource");
                if (ruleCheckList.size() > 0) {
                    Map ruleCheckMap = ruleCheckList.get(0);
                    Rule_Id = ruleCheckMap.get("Rule_Id");
                    String Rule_Name = ruleCheckMap.get("Rule_Name");
                    String Rolegroup = ruleCheckMap.get("Rolegroup");
                    String Staff_Id = ruleCheckMap.get("Staff_Id");
                    String Order_Adjustment = ruleCheckMap.get("Order_Adjustment");
                    log.debug("[输出获取规则信息] 规则ID:" + Rule_Id + " 规则名:" + Rule_Name + " 下发组:" + Rolegroup + " 下发人:" + Staff_Id + " 优先级:" + Order_Adjustment);

                    // 初始化规则下发
                    ruleAssignInit(eliteBean, Rule_Id);

                    // 取当前名单下发最少的坐席（不支持一人多组）
                    String getAssginStaffSQL = "Select R1.Rec_Id, R2.Rolegroup_Id, R1.Staff_Id, R3.counselor_id" +
                            "  From Hst_Rule_Issue_Control R1" +
                            "  Left Join Staffrolegroup R2" +
                            "    On R1.Staff_Id = R2.Staff_Id" +
                            "  Left Join Staff R3" +
                            "    On R1.Staff_Id = R3.Staff_Id" +
                            " Where Rule_Id = " + Rule_Id + "" +
                            "   And Assign_Date = Date_Format(Now(), '%Y-%m-%d')" +
                            " Order By Assign_Num,Staff_Id Limit 1";
                    List getAssginStaffList = eliteBean.chaxun_sql(getAssginStaffSQL, "dataSource");

                    if(getAssginStaffList.size()>0){
                        Map getAssginStaffMap = getAssginStaffList.get(0);
                        r_Control_Id = getAssginStaffMap.get("Rec_Id");
                        r_Rolegroup_Id = getAssginStaffMap.get("Rolegroup_Id");
                        r_Staff_Id = getAssginStaffMap.get("Staff_Id");
                        counselor_id = getAssginStaffMap.get("counselor_id");// TODO 调用绑定接口是能与内部系统同步的员工ID
                        log.debug("[当前名单下发人信息] Rolegroup_Id:" + r_Rolegroup_Id + " Staff_Id:" + r_Staff_Id);
                    }else{
                        r_Rolegroup_Id = '';
                        r_Staff_Id = '';
                        log.debug("[当前名单下发人信息] 无组别人员 默认不分配 进入未分配数据池！");
                    }


                } else {// TODO 默认名单下发人需要结合业务实际修改
                    def obleaderSQL = "Select r_Rolegroup_Id, r_Staff_Id, counselor_id From hst_ob_leader Limit 1";
                    def obleaderresult = eliteBean.chaxun_sql(obleaderSQL, "dataSource");
                    if (obleaderresult.size() > 0) {
                        r_Rolegroup_Id = obleaderresult.get(0).get("r_Rolegroup_Id");
                        r_Staff_Id = obleaderresult.get(0).get("r_Staff_Id");
                        counselor_id = obleaderresult.get(0).get("counselor_id");
                    }else{// TODO 系统层面兜底
                        r_Rolegroup_Id = "";
                        r_Staff_Id = "";
                        counselor_id = "";
                    }
                    r_Control_Id = "-9999";
                    log.debug("[输出获取信息] r_Control_Id:" + r_Control_Id + " r_Rolegroup_Id:" + r_Rolegroup_Id + " r_Staff_Id:" + r_Staff_Id + " counselor_id:" + counselor_id );
                    log.debug("未查询到规则，名单下发到默认管理员，由管理员手动下发");
                }

                //判断当前客户是否属于邀约客户，属于则将名单直接下发给对应服务顾问
                if(Inviter_Hstno!=''&&Inviter_Hstno!=null){
                    String fwgw_id,staff_id,rolegroup_id,control_id="";
                    //查询当前客户 邀约客户对应的服务顾问
                    def getSelectfwgwidSQL = eliteBean.chaxun_sql("select s.counselor_id as fwgw_id,s.staff_id as staff_id,s.DEFAULTROLEGROUP as rolegroup_id from objective o   LEFT JOIN CUSTOMER c on c.customer_guid=o.customer_guid  LEFT JOIN staff s on s.STAFF_ID=o.HANDLEBY_ID where 1=1 and s.Workstatus = 'ONLINE' and o.Map_Id='MY48ZX' and c.CUSTOMER_ID ='" + Inviter_Hstno + "'", "dataSource");
                    log.debug("查询当前名单的邀约客户绑定的服务顾问 SQL:" + getSelectfwgwidSQL + " 结果数量:" + getSelectfwgwidSQL.size());

                    if(getSelectfwgwidSQL.size() > 0) {
                        fwgw_id = getSelectfwgwidSQL.get(0).get("fwgw_id");//服务顾问核心系统id
                        staff_id = getSelectfwgwidSQL.get(0).get("staff_id");//分配人员staffid
                        rolegroup_id = getSelectfwgwidSQL.get(0).get("rolegroup_id");//分配人员组别
                        log.debug("查询当前名单的邀约客户绑定的服务顾问结果:" + fwgw_id+"&人员控制ID:"+staff_id+"&rolegroup_id:"+rolegroup_id);
                        if(fwgw_id!=''&&fwgw_id!=null){
                            counselor_id=fwgw_id;
                            r_Control_Id='0000';
                            //Rule_Id="0";//邀约
                            r_Staff_Id=staff_id;
                            r_Rolegroup_Id=rolegroup_id;
                            log.debug("当前名单服务顾问直接更换为邀约客户的服务顾问id:" + counselor_id +"&人员控制ID:"+r_Staff_Id+"&rolegroup_id:"+r_Rolegroup_Id);
                            //String assignLog = "开户自动下发-名单ID:" + Rec_Id + "&规则ID:" + Rule_Id + "邀约&人员控制ID:" + r_Control_Id + "&任务TaskGuid:" + EliteTask_Guid;
                        }else{
                            log.debug("当前名单服务顾问按均分逻辑派发！");
                        }
                    }else{
                        fwgw_id = "";
                    }

                }
                //判断当前规则维护 组人是否有值 没有则进入未分配池 存在则按规则分配
                if((r_Rolegroup_Id==''||r_Rolegroup_Id==null)&&(r_Staff_Id==''||r_Staff_Id==null)){
                    //新客户入库 进入未分配池
                    newCustomerDeal(eliteBean, Rec_Id, Rule_Id, r_Control_Id, r_Rolegroup_Id, r_Staff_Id,Inviter_Hstno);

                }else if (dealBindCustTOStaff(Customerid, counselor_id)) {// 如果绑定客户&服务顾问成功
                    //绑定成功 新客户入库
                    boolean newCustDeal = newCustomerDeal(eliteBean, Rec_Id, Rule_Id, r_Control_Id, r_Rolegroup_Id, r_Staff_Id,Inviter_Hstno);
					
					//给邀约客户 累计邀请客户数【】 sq_12默认初始值是从0开始
                    if(Inviter_Hstno!=''&&Inviter_Hstno!=null) {
                           eliteBean.update("Update customer Set sq_12 = sq_12+1 Where customer_id ='"+Inviter_Hstno+"'", "dataSource");
                    }
					
                    if (newCustDeal) {
                        // 更新规则下发记录
                        long endTime = System.currentTimeMillis();
                        String updateCustSQL = "Update Account_Information Set Deal_Time = Now(), Deal_Flag = 1, Deal_Result = '新建下发成功-耗时:" + (endTime - startTime) + "' Where Rec_Id = " + Rec_Id;
                        log.debug("下发成功-耗时:"+(endTime - startTime));
                        eliteBean.update(updateCustSQL, "dataSource");
                    } else {

                        long endTime = System.currentTimeMillis();
                        String updateCustSQL = "Update Account_Information Set Deal_Time = Now(), Deal_Flag = -1, Deal_Result = '新建下发失败-耗时:" + (endTime - startTime) + "' Where Rec_Id = " + Rec_Id;
                        eliteBean.update(updateCustSQL, "dataSource");
                        log.warn("新建客户&任务失败-耗时:"+(endTime - startTime));
                    }

                } else {
                    long endTime = System.currentTimeMillis();
                    String updateCustSQL = "Update Account_Information Set Deal_Time = Now(), Deal_Flag = -2, Deal_Result = '绑定服务顾问失败-耗时:" + (endTime - startTime) + "' Where Rec_Id = " + Rec_Id;
                    eliteBean.update(updateCustSQL, "dataSource");
                    log.warn("绑定服务顾问失败-耗时:"+(endTime - startTime));
                }


            } else {
                // 名单已经存在
                Map custCountMap = custCountList.get(0);

                long endTime = System.currentTimeMillis();
                String updateCustSQL = "Update Account_Information Set Deal_Time = Now(), Deal_Flag = -3, Deal_Result = '当前开户客户的华盛号系统已经存在...当前任务华盛号：" + Customerid + " 系统已存在客户Customer_Guid：" + custCountMap.get("Customer_Guid")+ "-耗时:"+(endTime - startTime) + "' Where Rec_Id = " + Rec_Id;
                eliteBean.update(updateCustSQL, "dataSource");

                log.debug("当前开户客户的华盛号系统已经存在...当前任务华盛号：" + Customerid + " 系统已存在客户Customer_Guid：" + custCountMap.get("Customer_Guid")+ "-耗时:"+(endTime - startTime));

                // TODO 待补充已存在名单的下发逻辑

            }


        }
        return 1;
    }

    /**
     * 规则下发数据初始化
     * @param eliteBean
     * @param Rule_Id
     * @return
     */
    public static boolean ruleAssignInit(EliteBean eliteBean, String Rule_Id) {
        boolean reFlag = true;
		
		//新增判断坐席B岗接任时间的逻辑截止状态、及离职人员默认不分配
		//A.-如果有离职人员 则直接关闭其分配状态-- 是否开启自动分配 0开启 1关闭
		String updatestaffstate1SQL = "update staff" +
                " set auto_allocation=1 " +
                " Where auto_allocation=0 " +
                "   And workstatus!='ONLINE'";
        eliteBean.update(updatestaffstate1SQL, "dataSource");
		
		//B.-如果有B岗角色接任时间到期 则更新企状态为自动开启分配 +清空时间维护
		String updatestaffstate2SQL = "update staff" +
                " set auto_allocation=0,starttime=null,endtime=null " +
                " Where auto_allocation=1 " +
                " 	And starttime <now()" +
                "   And endtime<now()";
        eliteBean.update(updatestaffstate2SQL, "dataSource");

        // 初始化（1~4）下发记录表（这里默认按每天清零）
        // 1-查找当前规则配置的坐席
        String ruleStaffSQL = "Select Case" +
                "         When R1.Staff_Id Is Null Or R1.Staff_Id = '' Then" +
                "          R2.Staff_Id" +
                "         Else" +
                "          R1.Staff_Id" +
                "       End As ruleStaff" +
                "  From Hst_Rule_Issue R1" +
                "  Left Join (Select R4.Rule_Id, Group_Concat(Distinct R3.Staff_Id) As Staff_Id" +
                "               From Rolegroup R1" +
                "               Left Join Staffrolegroup R2" +
                "                 On R1.Rolegroup_Id = R2.Rolegroup_Id" +
                "               Left Join Staff R3" +
                "                 On R2.Staff_Id = R3.Staff_Id" +
                "               Left Join Hst_Rule_Issue R4" +
                "                 On Find_In_Set(R1.Rolegroup_Id, R4.Rolegroup) > 0" +
                "              Where R1.Status = 1" +
                "                And ((R3.auto_allocation = 0) " +
				" 				or (R3.auto_allocation = 1 And R3.starttime>now() And R3.endtime>now() And R3.starttime is not null And R3.endtime is not null)" +
				" 				or (R3.auto_allocation = 1 And R3.starttime<now() And R3.endtime<now() And R3.starttime is not null And R3.endtime is not null))" +
                "                And R3.Workstatus = 'ONLINE'" +
                "                And R4.Rule_Id = " + Rule_Id + ") R2" +
                "    On R1.Rule_Id = R2.Rule_Id" +
                "   And (R1.Staff_Id Is Null Or R1.Staff_Id = '')" +
                " Where R1.Rule_Id = " + Rule_Id + "";

        List ruleStaffList = eliteBean.chaxun_sql(ruleStaffSQL, "dataSource");

        Map ruleStaffMap = ruleStaffList.get(0);
        log.debug("ruleStaffMap:    "+ruleStaffMap);
        String ruleStaff = ruleStaffMap.get("ruleStaff");
        log.debug("ruleStaff:    "+ruleStaff);
        //处理Assign_Num
        def selectassignnumSQL = "select case when count(*)=0 then 0 else  round(sum(assign_num)/count(*)) end as assignnum from hst_rule_issue_control  Where Rule_Id = " + Rule_Id + "  And Assign_Date = Date_Format(Now(), '%Y-%m-%d')";
        def selectassignnumresult = eliteBean.chaxun_sql(selectassignnumSQL, "dataSource");
        def assignnum =0;
        if (selectassignnumresult.size() > 0) {
            assignnum = selectassignnumresult.get(0).get("assignnum");
        }
        log.debug("assignnum:    "+assignnum);

        // 2-将不在下发规则表中不存在的坐席补充，防止中途规则配置的人或组修改添加
        String insertStaffSQL = "Insert Into Hst_Rule_Issue_Control" +
                "  (Rule_Id, Staff_Id, Assign_Date, Assign_Num,assign_yynum, Last_Check_Time)" +
                "  Select " + Rule_Id + ", Staff_Id, Date_Format(Now(), '%Y-%m-%d'), '" + assignnum + "', 0, Now()" +
                "    From Staff" +
                "   Where Find_In_Set(Staff_Id, '" + ruleStaff + "') > 0" +
                "     And Staff_Id Not In (Select Staff_Id" +
                "                            From Hst_Rule_Issue_Control" +
                "                           Where Rule_Id = " + Rule_Id + "" +
                "                             And Assign_Date = Date_Format(Now(), '%Y-%m-%d'))";
        int newStaffNum = eliteBean.update(insertStaffSQL, "dataSource");

        // 3-将不需要不满足下发的坐席删除，防止中途规则配置的人或组删除
        String deleteStaffSQL = "Delete From Hst_Rule_Issue_Control" +
                " Where Staff_Id Not In" +
                "       (Select Staff_Id" +
                "          From Staff" +
                "         Where Find_In_Set(Staff_Id, '" + ruleStaff + "') > 0" +
                "   And ((auto_allocation = 0) " +
				" 	or (auto_allocation = 1 And starttime>now() And endtime>now() And starttime is not null And endtime is not null)" +
				" 	or (auto_allocation = 1 And starttime<now() And endtime<now() And starttime is not null And endtime is not null))" +
                "   And Workstatus = 'ONLINE')"+
                "   And Rule_Id = " + Rule_Id + ""+
                "   And Assign_Date = Date_Format(Now(), '%Y-%m-%d')";
        eliteBean.update(deleteStaffSQL, "dataSource");
		
        // 4-如果有新加的人员将规则坐席已下发数量全部归零
        /*
        if (newStaffNum > 0) {
            String updateAssignNum = "Update Hst_Rule_Issue_Control" +
                    "   Set Assign_Num = 0,assign_yynum = 0, Last_Check_Time = Now()" +
                    " Where Rule_Id = " + Rule_Id + "" +
                    "   And Assign_Date = Date_Format(Now(), '%Y-%m-%d')";
            eliteBean.update(updateAssignNum, "dataSource");
        }
        */

        return reFlag;
    }

    /**
     * 新客户入库
     * @param eliteBean
     * @param Rule_Id
     * @return
     */
    public static boolean newCustomerDeal(EliteBean eliteBean, String Rec_Id, String Rule_Id, String r_Control_Id, String r_Rolegroup_Id, String r_Staff_Id, String Inviter_Hstno) {
        boolean reFlag = true;

        try {
            // 生成相关ID
            String Temp_Guid = KHUtil.getRandomString(31).toUpperCase();
            String Customer_Guid = "CUST_" + Temp_Guid;
            String Objective_Guid = "OBJE_" + Temp_Guid;
            String EliteTask_Guid = "TASK_" + Temp_Guid;

            String[] custTaskDealSQL = new String[6];
            // 插入Customer表
            custTaskDealSQL[0] = "Insert Into Customer" +
                    "  (Customer_Guid," +
                    "   Customer_Id," +
                    "   Customername," +
                    "   Gender," +
                    "   Mobile," +
                    "   Sq_2," +
                    "   Stringfield3," +
                    "   Stringfield13," +
                    "   sq_9," +
                    "   Stringfield7," +
                    "   Stringfield8," +
                    "   Sq_5," +
                    "   Sq_6," +
                    "   Sq_7," +
                    "   Createdby," +
                    "   Createddate)" +
                    "  Select '" + Customer_Guid + "'," +
                    "         Customerid," +
                    "         Customername," +
                    "         Gender," +
                    "         Phone," +
                    "         Accounttype," +
                    "         tradepermission," +
                    "         Register," +
                    "         register_id," +
                    "         Registertime," +
                    "         Opentime," +
                    "         Inviter_Hstno," +
                    "         Inviter_Name," +
                    "         Inviter_Type," +
                    "         'SELITE'," +
                    "         Now()" +
                    "    From Account_Information" +
                    "   Where Rec_Id = '"+Rec_Id+"'"

            // 插入Objective表
            custTaskDealSQL[1] = "Insert Into Objective" +
                    "  (Objective_Guid," +
                    "   Objectivetype_Id," +
                    "   Handleby_Id," +
                    "   Handlegroup_Id," +
                    "   Priority_Id," +
                    "   Expireddate," +
                    "   Customer_Guid," +
                    "   Objectivestatus," +
                    "   Iscontact," +
                    "   Trytimes," +
                    "   Successfulcontacttimes," +
                    "   Createdby," +
                    "   Createddate," +
                    "   Obstatus," +
                    "   Failure_Attempt," +
                    "   Contact_Customer_Guid," +
                    "   Passflag," +
                    "   Lastassigndate," +
                    "   Failstatus," +
                    "   Successstatus," +
                    "   Owner," +
                    "   Workorderframe_Id," +
                    "   Category," +
                    "   Forecastdate," +
                    "   Workorderid," +
                    "   Workordertype1," +
                    "   Workordertype2," +
                    "   Workordertype3," +
                    "   Workordertype4," +
                    "   Objectivesubstatus," +
                    "   Map_Id," +
                    "   Curstep_Id_Map," +
                    "   Max_Attempt," +
                    "   Nocontacttry," +
                    "   Allocation_Pool," +
                    "   Appointment)" +
                    "Values" +
                    "  ('" + Objective_Guid + "'," +
                    "   'RE0TX1'," +
                    "   '" + r_Staff_Id + "'," +
                    "   '" + r_Rolegroup_Id + "'," +
                    "   'NORMAL'," +
                    "   Date_Add(Now(), Interval 1 Day)," +
                    "   '" + Customer_Guid + "'," +
                    "   'OPEN'," +
                    "   0," +
                    "   0," +
                    "   0," +
                    "   'SELITE'," +
                    "   Now()," +
                    "   'OPEN'," +
                    "   999," +
                    "   ''," +
                    "   0," +
                    "   Null," +
                    "   '0'," +
                    "   '0'," +
                    "   ''," +
                    "   'MY48ZX'," +
                    "   'CASE'," +
                    "   '2021-04-25 17:59:35'," +
                    "   Concat('HS', Date_Format(Now(), '%Y%m%d%H'), '-', Lpad(Floor(Rand() * 10000), 4, '0'))," +
                    "   'QL800E'," +
                    "   'O7JIUV'," +
                    "   ''," +
                    "   ''," +
                    "   'OPEN'," +
                    "   'MY48ZX'," +
                    "   'ONA0KD'," +
                    "   0," +
                    "   0," +
                    "   0," +
                    "   0)";

            // 插入EliteTask表
            custTaskDealSQL[2] = "Insert Into Elitetask" +
                    "  (Elitetask_Guid," +
                    "   Objective_Guid," +
                    "   Objectivetype_Id," +
                    "   Expectstarttime," +
                    "   Expectendtime," +
                    "   Obstatus," +
                    "   Recordstatus," +
                    "   Attempt," +
                    "   Max_Attempt," +
                    "   Handleby_Id," +
                    "   Handlegroup_Id," +
                    "   Createdby," +
                    "   Createddate," +
                    "   Failure_Attempt," +
                    "   Comments," +
                    "   Customer_Guid," +
                    "   Localtrycount," +
                    "   Lastassigndate," +
                    "   Workorderframe_Id," +
                    "   Curstepstatus," +
                    "   Curstep_Id," +
                    "   Stepforecastdate," +
                    "   Curstep_Id_Map," +
                    "   Map_Id," +
                    "   Objectivesubstatus," +
                    "   Elitetaskstatus," +
                    "   Obflag,Maintaskstep_Id_Map)" +
                    "Values" +
                    "  ('" + EliteTask_Guid + "'," +
                    "   '" + Objective_Guid + "'," +
                    "   'RE0TX1'," +
                    "   Now()," +
                    "   Date_Add(Now(), Interval 3 Day)," +
                    "   'OPEN'," +
                    "   0," +
                    "   1," +
                    "   999," +
                    "   '" + r_Staff_Id + "'," +
                    "   '" + r_Rolegroup_Id + "'," +
                    "   'SELITE'," +
                    "   Now()," +
                    "   999," +
                    "   ''," +
                    "   '" + Customer_Guid + "'," +
                    "   0," +
                    "   Now()," +
                    "   ''," +
                    "   'OPEN'," +
                    "   'ONA0KD'," +
                    "   Now()," +
                    "   'ONA0KD'," +
                    "   'MY48ZX'," +
                    "   'OPEN'," +
                    "   'OPEN'," +
                    "   1,'ONA0KD')";

            // 插入Assign_His表
            String assignLog = "开户自动下发-名单ID:" + Rec_Id + "&规则ID:" + Rule_Id + "&人员控制ID:" + r_Control_Id + "&任务TaskGuid:" + EliteTask_Guid;
            log.debug(assignLog);
            //判断是否需要入池分配
			log.debug(Inviter_Hstno+":===Inviter_Hstno+长度"+Inviter_Hstno.length())
            if((r_Rolegroup_Id==''||r_Rolegroup_Id==null)&&(r_Staff_Id==''||r_Staff_Id==null)){
                log.debug("仅入未分配池库！");
            }else if((r_Rolegroup_Id!=''||r_Rolegroup_Id!=null)&&(r_Staff_Id!=''||r_Staff_Id!=null)&&( Inviter_Hstno!=null && Inviter_Hstno.length() > 0 )){
				log.debug("仅入属客户邀约！");
				custTaskDealSQL[3] = "Insert Into Assign_His (Assign_Guid, Customer_Guid, Objective_Guid, Oldhandlegroup_Id, Oldhandleby_Id, Newhandlegroup_Id, Newhandleby_Id, Assigngroup_Id, Assignby_Id, Assigndate, Success_Guid) Values (Uuid(), '" + Customer_Guid + "', '" + Objective_Guid + "', Null, Null, '" + r_Rolegroup_Id + "', '" + r_Staff_Id + "', 'SYSTEM', 'SELITE', Now(), '" + assignLog + "')";
            }else{
                custTaskDealSQL[3] = "Insert Into Assign_His (Assign_Guid, Customer_Guid, Objective_Guid, Oldhandlegroup_Id, Oldhandleby_Id, Newhandlegroup_Id, Newhandleby_Id, Assigngroup_Id, Assignby_Id, Assigndate, Success_Guid) Values (Uuid(), '" + Customer_Guid + "', '" + Objective_Guid + "', Null, Null, '" + r_Rolegroup_Id + "', '" + r_Staff_Id + "', 'SYSTEM', 'SELITE', Now(), '" + assignLog + "')";

                // 更新下发中间表
                //如存在邀约华盛号，则说明当前名单属于邀约类型 不计入均分策略
                if(Inviter_Hstno!=''&&Inviter_Hstno!=null) {
                    custTaskDealSQL[4] = "Update Hst_Rule_Issue_Control Set assign_yynum = assign_yynum + 1, Last_Check_Time = Now() Where Rec_Id = " + r_Control_Id;
                    custTaskDealSQL[5] = "Update Hst_Rule_Issue Set assign_yynum = Ifnull(assign_yynum, 0) + 1, Today_Assign_Num = Case When Today_Assign_Date = Date_Format(Now(), '%Y-%m-%d') Then Ifnull(Today_Assign_Num, 0) + 1 Else 1 End, Today_Assign_Date " +
                            "= Case When Today_Assign_Date = Date_Format(Now(), '%Y-%m-%d') Then Today_Assign_Date Else Date_Format(Now(), '%Y-%m-%d') End Where Rule_Id = " + Rule_Id + "";
                }else{
                    custTaskDealSQL[4] = "Update Hst_Rule_Issue_Control Set Assign_Num = Assign_Num + 1, Last_Check_Time = Now() Where Rec_Id = " + r_Control_Id;
                    custTaskDealSQL[5] = "Update Hst_Rule_Issue Set Assign_Num = Ifnull(Assign_Num, 0) + 1, Today_Assign_Num = Case When Today_Assign_Date = Date_Format(Now(), '%Y-%m-%d') Then Ifnull(Today_Assign_Num, 0) + 1 Else 1 End, Today_Assign_Date " +
                            "= Case When Today_Assign_Date = Date_Format(Now(), '%Y-%m-%d') Then Today_Assign_Date Else Date_Format(Now(), '%Y-%m-%d') End Where Rule_Id = " + Rule_Id + "";
                }
            }

            int[] batchSQLResult = eliteBean.updateBatch(custTaskDealSQL, "dataSource");
            log.debug("新客户入库批量处理SQL返回结果："+batchSQLResult.toString());

        } catch (Exception e) {
            log.error("新客户入库异常!", e);
            reFlag = false;
        }

        return reFlag;
    }

    /**
     * 调用接口同步华盛内部系统服务顾问绑定
     * @param eliteBean
     * @param Customerid
     * @param r_Rolegroup_Id
     * @param r_Staff_Id
     * @return
     */
    public static boolean dealBindCustTOStaff(String Customerid, String r_Loginname) {

        boolean reFlag = true;

        try{
            String injson = "{\"hsNo\":\""+Customerid+"\",\"managerId\":\""+r_Loginname+"\"}";
            Map<String, String> headMap = new HashMap<String, String>();
            headMap.put("Content-Type", "application/json");
            def sysurl = getProperty.get("crmurl");//配置本地接口地址
            sysurl = sysurl+"aipHSTBindCounselor";
            def getResult =Util.doHttpPostUseHead(sysurl,injson,"UTF-8",100000,0,headMap);
            log.debug("绑定接口返回："+getResult);

            JSONObject jsonObject = new JSONObject(getResult);
            String code = GetJV(jsonObject, "result");
            log.debug("绑定接口返回code："+code);
            if(code == "1") {
                reFlag=true;
            }else{
                reFlag=false;
            }
        } catch (Exception e) {
            log.error("绑定客户异常!", e);
            reFlag = false;
        }
        log.debug("reFlag："+reFlag);
        return reFlag;
    }

    // 解析Json值
    public static String GetJV(JSONObject inJson, String getKey) {
        String Rev_Value = null;
        try {
            Rev_Value = inJson.getString(getKey);
        } catch (Exception e) {
            try {
                Rev_Value = String.valueOf(inJson.getInt(getKey));
            } catch (Exception e1) {
                try {
                    Rev_Value = String.valueOf(inJson.getJSONArray(getKey));
                } catch (Exception e2) {
                    try {
                        Rev_Value = String.valueOf(inJson.getJSONObject(getKey));
                    } catch (Exception e3) {
                        Rev_Value = "";
                    }
                }
            }
        } finally {
            if (Rev_Value == null || Rev_Value.equals("null") || Rev_Value.length() <= 0) {
                Rev_Value = "";
            } else {
            }
        }
        log.debug("解析-k=" + getKey + " v=" + Rev_Value);
        return Rev_Value;
    }
}